<template>
	<view class="pl-20 pr-20 pt-20">
		<view>
			<u-alert title="请选择小于5M的图片进行裁剪上传" type="primary"></u-alert>
		</view>
		<view>
			<u-divider text="封面图"></u-divider>
			<u-upload
				:fileList="fileList1"
				@afterRead="afterRead"
				@delete="deletePic"
				name="1"
				multiple
				:maxCount="1"
			></u-upload>
		</view>
		<view>
			<u-divider text="图集"></u-divider>
			<u-upload
				:fileList="fileList2"
				@afterRead="afterRead"
				@delete="deletePic"
				name="2"
				multiple
			></u-upload>
		</view>
		<view>
			<u-divider text="媒体"></u-divider>
			<view class="flex align-center">
				<text class="mr-20">视频</text>
				<u-input
					placeholder="请输入视频地址"
					v-model="file.video"
					border="bottom"
				></u-input>
			</view>
			<view class="mt-20 line-gray fsize-28">支持常用视频播放格式</view>
			<!-- <u-upload
				:fileList="fileList3"
				@afterRead="afterRead"
				@delete="deletePic"
				name="3"
				multiple
				accept="video"
			></u-upload> -->
		</view>
	</view>
</template>

<script>
	export default {
		data () {
			return {
				fileList1:[],
				fileList2:[],
				file: {
					image: '',
					images: [],
					video:''
				}
			}
		},
		watch: {
			file: {
				deep: true, // 深度监听，包括子对象的变化
				handler(newVal){
					this.$emit('update:file', newVal)
				}
			}
		},
		methods: {
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				if(event.name==='1'){
					this.file.image = ''
				}else {
					if(this.fileList2.length > 0){
						this.file.images = this.fileList2.map(im=>im.url)
					}
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.$reqUpLoad(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					if(event.name === '1'){
						this.file.image = result.fileUrl
					}else if(event.name === '2') {
						if(this.file.images.length === 0){
							this.file.images = [result.fileUrl]
						}else {
							this.file.images.push(result.fileUrl)
						}
					}
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result.fileUrl
					}))
					fileListLen++
				}
			},
			
		}
	}
</script>

<style>
	
</style>